package com.iotteam.androidbase.commen.utils;

import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Type;

/**
 * Created by lidechen on 5/5/17.
 */

public class ObjectUtil {

    // 对象转为Base64
    public static String objectToBase64Code(Object o) {
        String rtn = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(o);
            rtn = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
        } catch (Exception e) {
            // : handle exception
            e.printStackTrace();
            rtn = null;
        } finally {
            try {
                baos.close();

                oos.close();
            } catch (IOException e) {
                // Auto-generated catch block
                e.printStackTrace();
            }
        }

        return rtn;
    }

    // Base64转为对象
    @SuppressWarnings("unchecked")
    public static <T> T base64codeToObject(String scr) {
        byte[] bt = Base64.decode(scr, Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(bt);
        ObjectInputStream ois = null;
        T ot = null;
        try {
            ois = new ObjectInputStream(bais);
            ot = (T) ois.readObject();
        } catch (Exception e) {
            // : handle exception
            ot = null;
        } finally {
            try {
                bais.close();
                ois.close();
            } catch (IOException e) {
                // Auto-generated catch block
                e.printStackTrace();
            }

        }
        return ot;
    }

}
